<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Resources\CatesResourceCollection;
use App\Models\Cates;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Category extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view("admin.category.index");
    }

    public function getCates(Request $request)
    {
       $cates = Cates::orderBy('cate_sort','desc')->get();
       $cates = new CatesResourceCollection($cates);
       $total = Cates::all()->count();
       return response()->json(['code'=>0,'data'=>$cates,'count'=>$total]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('admin.category.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $params = $request->except(['_token','s']);
        $data = Cates::where('cate_name','=',$params['cate_name'])->exists();
        if($data){
            return response()->json(['status'=>201,'msg'=>'该分类已存在']);
        }else{
            Cates::create($params);
            return response()->json(['status'=>200,'msg'=>"添加成功"]);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $cate = Cates::where('id',$id)->first();
        return view('admin.category.edit',compact('cate'));
    }

    //更新数据
    public function update(Request $request, $id)
    {
        $params = $request->except(['_token','s']);
        $state = Cates::where('id','=',$id)->update($params);
        if($state){
            return response()->json(['status'=>200,'msg'=>"修改成功"]);
        }else{
            return response()->json(['status'=>201,'msg'=>"修改失败"]);
        }
    }

    //删除数据
    public function destroy($id)
    {
        $state = Cates::where('id','=',$id)->delete();
        if($state){
            return response()->json(['status'=>200,'msg'=>"删除成功"]);
        }else{
            return response()->json(['status'=>201,'msg'=>"删除失败"]);
        }
    }
}
